import { RequestDTO } from "@/dto/general";

// 打开接收消息的端口
const startListeningPort = () => {
  browser.runtime.onConnect.addListener((port) => {
    port.onMessage.addListener((message: RequestDTO, port) => {
      if (message.to === "background") {
        if (port.name == "popup") {
          dealPopup(message);
        } else if (port.name == "content") {
          dealContent(message, port);
        }
      }
    });
  });
};

const dealPopup = (message: RequestDTO, ) => {
  console.log("BG - receive from popup:" + JSON.stringify(message));
  var port = browser.runtime.connect({"name": "background"})
  var message: RequestDTO = new RequestDTO("background", "popup", {"background": "iuuuuuu"}, "doSome")
  port.postMessage(message)
};

const dealContent = (message: RequestDTO, port: chrome.runtime.Port) => {
  console.log("BG - receive from content:" + JSON.stringify(message));
};

export default defineBackground(() => {
  console.log("Hello background!", { id: browser.runtime.id });
  startListeningPort();
});
